import sys
import pygame

from bullet import Bullet
from alien import Alien
from time import sleep


# 退出游戏事件
def check_events(ai_settings, screen, stats, scoreboard, play_button, ship, aliens, bullets):
    # 监视键盘和鼠标
    for event in pygame.event.get():
        # 当玩家关闭窗口时退出游戏
        if event.type == pygame.QUIT:
            sys.exit()
        # 按下按键事件监听
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        # 松开按键事件监听
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        # 按键监听
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, scoreboard, play_button, ship, aliens, bullets, mouse_x, mouse_y)


# 点击按钮
def check_play_button(ai_settings, screen, stats, scoreboard, play_button, ship, aliens, bullets, mouse_x, mouse_y):
    # 玩家点击按钮时开始新游戏
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_clicked and not stats.game_active:
        # 重置游戏设置
        ai_settings.initialize_dynamic_settings()
        # 隐藏光标
        pygame.mouse.set_visible(False)
        # 重置游戏统计
        stats.reset_stats()
        stats.game_active = True
        # 重置记分牌的图像
        scoreboard.prep_score()
        scoreboard.prep_high_score()
        scoreboard.prep_level()
        scoreboard.prep_ships()
        # 清空敌人和子弹
        aliens.empty()
        bullets.empty()
        # 重新创建一群敌人，并重置一个飞船
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()


# 按下按键事件
def check_keydown_events(event, ai_settings, screen, ship, bullets):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    # 按下空格事件监听（发射子弹）
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, screen, ship, bullets)
    # 按键退出游戏
    elif event.key == pygame.K_ESCAPE:
        sys.exit()


# 松开按键事件
def check_keyup_events(event, ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


# 更新图像，并切换到新的屏幕
def update_screen(ai_settings, screen, stats, scoreboard, ship, bullets, aliens, background, play_button):
    # 每次绘制屏幕时加上背景色并设置宽度
    screen.fill(ai_settings.bg_color)
    screen.blit(background, (0, 0))
    # 在飞船后绘制所有子弹
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    # 绘制飞船
    ship.blitme()
    # 绘制敌人
    aliens.draw(screen)
    # 显示得分
    scoreboard.show_score()
    # 绘制paly按钮（非活动状态时）
    if not stats.game_active:
        play_button.draw_button()
    # 每次开始游戏时显示新的屏幕
    pygame.display.flip()


# 子弹相关逻辑
def update_bullets(ai_settings, screen, stats, scoreboard, ship, aliens, bullets):
    # 子弹移动
    bullets.update()
    # 删除屏幕外的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    check_bullet_alien_collisions(ai_settings, screen, stats, scoreboard, ship, aliens, bullets)


# 开火
def fire_bullet(ai_settings, screen, ship, bullets):
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)


# 计算每行可容纳多少敌人
def get_number_aliens_x(ai_settings, alien_width):
    avaliable_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(avaliable_space_x / (2 * alien_width))
    return number_aliens_x


# 计算屏幕可容纳多少行敌人
def get_number_rows(ai_settings, ship_height, alien_height):
    available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height)
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows


# 创建敌人
def create_alien(ai_settings, screen, aliens, alien_number, row_number):
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)


# 创建敌人群
def create_fleet(ai_settings, screen, ship, aliens):
    # 创建敌人组并计算一行的可容纳量
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
    number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_number, row_number)


# 检查边界
def check_fleet_edges(ai_settings, aliens):
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break


# 改变敌人运行方向
def change_fleet_direction(ai_settings, aliens):
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1


# 敌人撞到飞船
def ship_hit(ai_settings, stats, screen, scoreboard, ship, aliens, bullets):
    if stats.ships_left > 0:
        # 飞船血量-1
        stats.ships_left -= 1

        # 清空敌人和子弹
        aliens.empty()
        bullets.empty()

        # 重新创建一群敌人，并重置一个飞船
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

        # 暂停
        sleep(0.5)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)


# 敌人移动
def update_aliens(ai_settings, stats, scoreboard, screen, ship, aliens, bullets):
    # 检测到敌人位于屏幕边缘，调整位置
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    # 检测敌人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, screen, scoreboard, ship, aliens, bullets)
    # 检测是否有敌人到达底部
    check_aliens_bottom(ai_settings, stats, screen, scoreboard, ship, aliens, bullets)


# 检测子弹和敌人的碰撞
def check_bullet_alien_collisions(ai_settings, screen, stats, scoreboard, ship, aliens, bullets):
    # 检测是否有子弹击中了敌人，如果击中了就删除相应的子弹和敌人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(aliens)
            scoreboard.prep_score()
        check_high_score(stats, scoreboard)

    # 当敌人全部被消灭时
    if len(aliens) == 0:
        # 删除现有子弹，并创建一群新的敌人，增加游戏速度
        bullets.empty()
        ai_settings.increase_speed()
        # 提高等级
        stats.level += 1
        scoreboard.prep_level()
        create_fleet(ai_settings, screen, ship, aliens)


# 检测敌人到达底端
def check_aliens_bottom(ai_settings, stats, screen, scoreboard, ship, aliens, bullets):
    screen_rect = screen.get_rect()
    # 到达底部，就像飞船被撞击一样的处理
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            ship_hit(ai_settings, stats, screen, scoreboard, ship, aliens, bullets)
            break


# 检测是否出现了新的最高分
def check_high_score(stats, scoreboard):
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        scoreboard.prep_high_score()
